package com.siemens.industrial.web.mvc.dao.admin;

import com.siemens.industrial.model.admin.Metadata;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Types;
import java.util.List;

/**
 * Created by qupen on 2016/9/18.
 */
@Service
public class MetadataDao {
    @Resource
    JdbcTemplate jdbcTemplate;

    private static final String getMetadataListQuery = "SELECT * FROM `siemens`.`metadata` WHERE delete_time IS NULL;";
    private static final String addMetadataQuery = "INSERT INTO `siemens`.`metadata` (`meta_key`,`meta_definition`) VALUES (?,?);";
    private static final String getMetadataListByKeyQuery = "SELECT * FROM `siemens`.`metadata` WHERE `meta_key`=? AND `delete_time` IS NULL;";
    private static final String deleteMetadataListByKeyQuery ="UPDATE `siemens`.`metadata` SET `delete_time` = now() WHERE `meta_id` = ?;";
    private static final String recoverMetadata ="UPDATE `siemens`.`metadata` SET `meta_definition`=?,`delete_time`=NULL WHERE `meta_id`=?;";
    private static final String getAllByKey="SELECT * FROM `siemens`.`metadata` WHERE `meta_key`=?";
    public void save(Metadata metadata) {
        jdbcTemplate.update(addMetadataQuery, pss -> {
            pss.setString(1, metadata.getMetaKey());
            pss.setString(2, metadata.getMetaDefinition());
        });
    }
    private static final String findOneByMetaId="SELECT * FROM siemens.metadata where meta_id=? and delete_time is null;";

    private static final String updateOneByMetaId="UPDATE `siemens`.`metadata` SET `meta_definition`=? WHERE `meta_id`=?;";

    public List<Metadata> findAllByMetaKey(String key) {
        return jdbcTemplate.query(getMetadataListByKeyQuery, new String[]{key}, Metadata.getRowMapper());
    }

    public List<Metadata> findAllByKey(String key) {
        return jdbcTemplate.query(getAllByKey, new String[]{key}, Metadata.getRowMapper());
    }

    public List<Metadata> findAll() {
        return jdbcTemplate.query(getMetadataListQuery, Metadata.getRowMapper());
    }

    @Transactional
    public void delete(String metadataId) {
        jdbcTemplate.update(deleteMetadataListByKeyQuery,metadataId);
    }

    @Transactional
    public void recover(String metadataId,String definition){
        jdbcTemplate.update(recoverMetadata,definition,metadataId);
    }

    public Metadata findOneByMetaId(String metaId){
        try {
            return jdbcTemplate.queryForObject(findOneByMetaId,new Object[]{metaId},new int[]{Types.VARCHAR},Metadata.getRowMapper());
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Transactional
    public void updateById(String metaDefinition ,String metaId){
        jdbcTemplate.update(updateOneByMetaId,metaDefinition,metaId);
    }
}
